/*
@title: Chrome Dino
@author: unknown
@tags: []
@addedOn: 2024-01-01
@description: A recreation of Chrome's offline dinosaur game. Press 'w' to make the dinosaur jump over incoming cacti. Try to achieve the highest score possible without hitting any obstacles!
*/

const dino = "d"
const cactus = "c"

setLegend(
  [ dino, bitmap`
................
................
.....00000......
....0000000.....
...000000000....
...000000000....
...000000000....
...003000300....
...000000000....
....0000000.....
.....00000......
................
................
................
................
................`],
  [ cactus, bitmap`
................
................
................
....444444......
....404404......
....444444......
....404404......
....444404......
....444444......
....404444......
....444404......
....444444......
................
................
................
................`]
)

let score = 0
let gameOver = false
let dinoVel = 0
const gravity = 1
const jumpStrength = -2

const groundY = 10
const maxX = 19

let spawnCooldown = 0

setMap(`
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
..d.................
`)

onInput("w", () => {
  if (!gameOver) {
    const dinoSprite = getFirst(dino)
    if (dinoSprite && dinoSprite.y === groundY) {
      dinoVel = jumpStrength
    }
  }
})

const gameInterval = setInterval(() => {
  if (gameOver) return

  let dinoSprite = getFirst(dino)
  if (dinoSprite) {
    dinoSprite.y += dinoVel
    dinoVel += gravity
    if (dinoSprite.y > groundY) {
      dinoSprite.y = groundY
      dinoVel = 0
    }
  }

  getAll(cactus).forEach((obs) => {
    obs.x -= 1
    if (!obs.scored && obs.x < getFirst(dino).x) {
      score++
      obs.scored = true
    }
    if (obs.x < 0) {
      destroy(obs)
    }
  })

  spawnCooldown--
  if (spawnCooldown <= 0) {
    let nearRight = getAll(cactus).some(o => o.x > maxX - 4)
    if (!nearRight && Math.random() < 0.3) {
      addSprite(maxX, groundY, cactus)
      spawnCooldown = Math.floor(Math.random() * 5) + 7
    }
  }

  if (tilesWith(dino, cactus).length > 0) {
    gameOver = true
    clearInterval(gameInterval)
    clearText()
    addText("Score: " + score, { x: 6, y: 4, color: color`3` })
  } else {
    clearText()
    addText("Score: " + score, { x: 0, y: 0, color: color`2` })
  }
}, 150)
